/*
 *
 *  * Copyright (C) 2015 Eason.Lai (easonline7@gmail.com)
 *  *
 *  * Licensed under the Apache License, Version 2.0 (the "License");
 *  * you may not use this file except in compliance with the License.
 *  * You may obtain a copy of the License at
 *  *
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  * Unless required by applicable law or agreed to in writing, software
 *  * distributed under the License is distributed on an "AS IS" BASIS,
 *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  * See the License for the specific language governing permissions and
 *  * limitations under the License.
 *
 */

package com.framework.seedkit.customwidget.imagePicker;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.framework.seedkit.R;
import com.pizidea.imagepicker.AndroidImagePicker;
import com.pizidea.imagepicker.ImgLoader;
import com.pizidea.imagepicker.UilImgLoader;
import com.pizidea.imagepicker.Util;
import com.pizidea.imagepicker.bean.ImageItem;
import com.pizidea.imagepicker.ui.activity.ImagesGridActivity;

import java.util.List;

public class ImagePickerAct extends FragmentActivity implements View.OnClickListener{
    private static final String TAG = ImagePickerAct.class.getSimpleName();
    public static final int REQUEST_MULTIPLE_PERMISSION = 1;
    private final int REQ_IMAGE = 1433;
    private final String[] applyPermissions = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS};

    private TextView btnSingle;
    private TextView btnMulti;
    private TextView btnCrop;
    private ImageView ivCrop;

    private CheckBox cbShowCamera;

    ImgLoader presenter = new UilImgLoader();
    GridView mGridView;
    SelectAdapter mAdapter;

    private int screenWidth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_img_picker_layout);

        btnSingle = (TextView) findViewById(R.id.btn_single);
        btnMulti = (TextView) findViewById(R.id.btn_multi);
        btnCrop = (TextView) findViewById(R.id.btn_crop);
        ivCrop = (ImageView) findViewById(R.id.iv_crop);
        cbShowCamera = (CheckBox) findViewById(R.id.cb_show_camera);
        mGridView = (GridView) findViewById(R.id.gridview);
        mAdapter = new SelectAdapter(this);
        mGridView.setAdapter(mAdapter);

        btnSingle.setOnClickListener(this);
        btnMulti.setOnClickListener(this);
        btnCrop.setOnClickListener(this);

        screenWidth = getWindowManager().getDefaultDisplay().getWidth();

        verifyIfRequestPermission();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onClick(View v) {

        Intent intent = new Intent();
        int requestCode = REQ_IMAGE;

        boolean isShowCamera = cbShowCamera.isChecked();


        switch (v.getId()){

            case R.id.btn_single:
                AndroidImagePicker.getInstance().pickSingle(ImagePickerAct.this, isShowCamera, new AndroidImagePicker.OnImagePickCompleteListener() {
                    @Override
                    public void onImagePickComplete(List<ImageItem> items) {
                        if(items != null && items.size() > 0){
                            Log.i(TAG,"=====选择了："+items.get(0).path);
                            mAdapter.clear();
                            mAdapter.addAll(items);
                        }
                    }
                });
                return;
            case R.id.btn_multi:
                AndroidImagePicker.getInstance().pickMulti(ImagePickerAct.this, isShowCamera, new AndroidImagePicker.OnImagePickCompleteListener() {
                    @Override
                    public void onImagePickComplete(List<ImageItem> items) {
                        if(items != null && items.size() > 0){
                            Log.i(TAG,"=====选择了："+items.get(0).path);
                            mAdapter.clear();
                            mAdapter.addAll(items);
                        }
                    }
                });
                return;

            case R.id.btn_crop:

                AndroidImagePicker.getInstance().pickAndCrop(ImagePickerAct.this, true, 120, new AndroidImagePicker.OnImageCropCompleteListener() {
                    @Override
                    public void onImageCropComplete(Bitmap bmp, float ratio) {
                        Log.i(TAG,"=====onImageCropComplete (get bitmap="+bmp.toString());
                        ivCrop.setVisibility(View.VISIBLE);
                        ivCrop.setImageBitmap(bmp);
                    }
                });

                return;
            default:
                break;

        }
        intent.setClass(this,ImagesGridActivity.class);
        startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(resultCode == Activity.RESULT_OK){
            if (requestCode == REQ_IMAGE) {
                ivCrop.setVisibility(View.GONE);

                List<ImageItem> imageList = AndroidImagePicker.getInstance().getSelectedImages();
                mAdapter.clear();
                mAdapter.addAll(imageList);
            }
        }

    }

    //Android 6.0权限请求
    private void verifyIfRequestPermission()
    {
        if (Build.VERSION.SDK_INT >= 23) {
            Log.i(TAG, "onCreate: checkSelfPermission");
            for (int i=0; i<applyPermissions.length; i++) {
                if (ContextCompat.checkSelfPermission(this,
                        applyPermissions[i])
                        != PackageManager.PERMISSION_GRANTED) {
                    Log.i(TAG, "onCreate: Android 6.0 动态申请权限");

                    if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                            applyPermissions[i])) {
                        Log.i(TAG, "*********onCreate: shouldShowRequestPermissionRationale**********");
                        Toast.makeText(this, "只有允许访问位置才能搜索到蓝牙设备", Toast.LENGTH_SHORT).show();
                    } else {
                        ActivityCompat.requestPermissions(this,
                                new String[]{applyPermissions[i]},
                                REQUEST_MULTIPLE_PERMISSION);
                    }
                } else {
//                showDialog(getResources().getString(R.string.scanning));
//                m_bleService.scanFfanBLEDevice(5000);
                }
            }
        }
    }

    //权限请求后的回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        if (requestCode == REQUEST_MULTIPLE_PERMISSION)
        {
            Log.i(TAG, "onRequestPermissionsResult: permissions.length = " + permissions.length +
                    ", grantResults.length = " + grantResults.length);
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted, yay! Do the
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(this, "位置访问权限被拒绝将无法搜索到ble设备", Toast.LENGTH_SHORT).show();
            }
        } else {

        }
    }

    class SelectAdapter extends ArrayAdapter<ImageItem>{

        //private int mResourceId;
        public SelectAdapter(Context context) {
            super(context, 0);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ImageItem item = getItem(position);
            LayoutInflater inflater = getLayoutInflater();
            int width = (screenWidth - Util.dp2px(ImagePickerAct.this,10*2))/3;

            ImageView imageView = new ImageView(ImagePickerAct.this);
            imageView.setBackgroundColor(Color.GRAY);
            GridView.LayoutParams params = new AbsListView.LayoutParams(width, width);
            imageView.setLayoutParams(params);

            presenter.onPresentImage(imageView,item.path,width);

            return imageView;
        }
    }

    @Override
    protected void onDestroy() {
        AndroidImagePicker.getInstance().onDestroy();
        super.onDestroy();
    }
}
